package com.easylinkin.linkappapi.grid.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.easylinkin.linkappapi.grid.entity.GridFile;
import com.easylinkin.linkappapi.grid.mapper.GridFileMapper;
import com.easylinkin.linkappapi.grid.models.dto.GridFileSaveDTO;
import com.easylinkin.linkappapi.grid.models.query.GridFileBatchQuery;
import com.easylinkin.linkappapi.grid.models.query.GridFileQuery;
import com.easylinkin.linkappapi.grid.models.vo.GridFileInfoVO;
import com.easylinkin.linkappapi.grid.service.IGridFileService;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 网格上传文件 服务实现类
 *
 * @author kuyujie
 * @since 2024-05-23
 */
@Validated
@Service
public class GridFileServiceImpl extends ServiceImpl<GridFileMapper, GridFile> implements IGridFileService {
    @Override
    public List<GridFileInfoVO> listInfoByQuery(@Validated GridFileQuery query) {
        return baseMapper.listInfoByQuery(query);
    }

    @Override
    public List<GridFileInfoVO> listInfoByBatchQuery(GridFileBatchQuery query) {
        return baseMapper.listInfoByBatchQuery(query);
    }

    @Override
    public Map<String, List<GridFileInfoVO>> mapListInfoByBatchQuery(GridFileBatchQuery query) {
        List<GridFileInfoVO> fileInfoVOS = baseMapper.listInfoByBatchQuery(query);
        if (CollUtil.isEmpty(fileInfoVOS)) {
            return Collections.emptyMap();
        }
        return fileInfoVOS.stream().collect(Collectors.groupingBy(item -> item.getBusId() + "," + item.getBusType() + "," + item.getBusSubType()));
    }

    @Override
    public long countByQuery(@Validated GridFileQuery query) {
        return baseMapper.countByQuery(query);
    }

    @Override
    public void saveDate(@Validated(GridFileSaveDTO.Save.class) GridFileSaveDTO dto) {
        if (StrUtil.isBlank(dto.getFileName()) && StrUtil.isNotBlank(dto.getFileUrl())) {
            String fileUrl = dto.getFileUrl();
            String fileName = fileUrl.substring(fileUrl.lastIndexOf("/") + 1);
            dto.setFileName(fileName);
        }

        GridFile entity = GridFile.builder()
                .busId(dto.getBusId())
                .busType(dto.getBusType())
                .busSubType(dto.getBusSubType())
                .busSubContent(dto.getBusSubContent())
                .fileUrl(dto.getFileUrl())
                .fileName(dto.getFileName())
                .build();

        this.save(entity);
    }

    @Override
    public void delById(Long id) {
        this.removeById(id);
    }
}